
'use strict';
var _ = require("lodash");
var constant = require('../utils/constant');
var log4js = require('log4js');
var log = log4js.getLogger("jipai");

exports.initChongFengJiConfig = function (game) {
    var chongfengJiList = game.conf.chongfengJi;
    if (chongfengJiList && chongfengJiList.length > 0) { // 更新冲锋鸡列表 
        game.chongFengJi = {};
        chongfengJiList.forEach(function (ji) {
            game.chongFengJi[ji] = {
                pais: constant.JiPai[ji],
                turnSeat: -1, //出鸡的位置
                chongPai: -1,
                zenRenJiType: -1 // 责任鸡的类型 
            };
        });
    }
};

/**
 * 检测并设置鸡牌
 * 
 * @param {Object} game 
 * @param {Object} seatData 
 * @param {Number} targetPai 
 * @returns {Boolean} chongFengJi
 */
exports.checkAndSetChongFengJiPai = function (game, seatIndex, targetPai, status) {
    // 如果玩家打出的牌是鸡牌，则记录

    var isChongFengJi = false;
    var jiPaiType = exports.getConfigJiPaiTypeByPai(game, targetPai);
    if (status) {
        if (jiPaiType !== -1 && game.chongFengJi && game.chongFengJi[jiPaiType]) {
            var seat = game.chongFengJi[jiPaiType].turnSeat;
            if (seat === -1) {
                game.chongFengJi[jiPaiType].turnSeat = seatIndex; // 记录谁打出鸡牌
                game.chongFengJi[jiPaiType].chongPai = targetPai; // 记录冲锋鸡的牌。
                isChongFengJi = true;
            }
        }
    }
    return {
        turnSeat: seatIndex,
        isChongFengJi: isChongFengJi,
        isjiPaiType: jiPaiType,
        pai: targetPai,
        isOper: false
    };
};

exports.setZeRenJiPaiSeat = function (game, seatIndex, targetPai) {
    var trunSeatIndex = -1;
    var jiPaiType = exports.getConfigJiPaiTypeByPai(game, targetPai);
    if (jiPaiType !== -1) {
        var seat = game.chongFengJi[jiPaiType].turnSeat;
        var zRJType = game.chongFengJi[jiPaiType].zenRenJiType;
        if (seat !== -1 && zRJType === -1 && game.chongFengJi[jiPaiType].chongPai === targetPai) {
            game.chongFengJi[jiPaiType].zenRenJiType = constant.CongJiPaiTypeCoverZrjPaiType[jiPaiType];
            trunSeatIndex = seat;
        }
    }
    return trunSeatIndex;
};


exports.getZenRenJiBySeatIndex = function (game, seatIndex) {
    var jiPaiTypes = {};
    jiPaiTypes.seatId = seatIndex;
    jiPaiTypes.types = [];
    for (var type in game.chongFengJi) {
        type = parseInt(type);
        var chongfengJi = game.chongFengJi[type];
        if (chongfengJi.chongPai !== -1) {
            if (chongfengJi.turnSeat === seatIndex) {
                if (chongfengJi.zenRenJiType === -1) {
                    jiPaiTypes.types.push(type);
                } else {
                    jiPaiTypes.types.push(chongfengJi.zenRenJiType);
                }
            }
        }
    }
    return jiPaiTypes;
};


exports.initJiPaiConfigRecord = function (game) {
    var jiPaiRule = game.conf.jiPaiRule;
    if (~jiPaiRule.indexOf(constant.JiType.ShangXiaJi)) {
        game.huPaiFanJi = [-1, -1, -1];
        game.shangXiaJi = true;
    }
    game.JiPaiRecord = [];
    game.chuJiPaiRecord = [];
    game.jiPaiList = [];
    for (var j = 0; j < jiPaiRule.length; j++) {
        if (jiPaiRule[j] !== constant.JiType.ShangXiaJi) {
            var pais = constant.JiPai[jiPaiRule[j]];
            game.jiPaiList = game.jiPaiList.concat(pais);
        }
    }
};


exports.getConfigJiPaiTypeByPai = function (game, pai) {
    pai = parseInt(pai);
    var indexPai = game.jiPaiList.indexOf(pai);
    if (indexPai !== -1) {
        for (var i in constant.JiPai) {
            if (~constant.JiPai[i].indexOf(pai)) {
                return i;
            }
        }
    }
    return -1;
};

// exports.insertChuJiPaiRecord = function (game, turnSeat, pai, type) {
//     game.chuJiPaiRecord.push({
//         turnSeat: turnSeat, // 出牌用户
//         pai: pai, //出的牌
//         type: type //鸡牌类型
//     });
// };

exports.insertJiPaiRecord = function (game, turnSeat, pai, operSeat, oper) {
    var type = constant.getJiPaiTypeByPai(pai);
    game.JiPaiRecord.push({
        turnSeat: turnSeat, // 出牌用户
        pai: pai, //出的牌
        type: type, //鸡牌类型
        operSeat: operSeat, //操作牌用户
        oper: oper // 操作
    });
    log.debug('list==>', game.JiPaiRecord);
};



var calculationJiPaiHoldsScore = function (game, roomInfo) {
    var JpaiNameMap = constant.JpaiNameMap;
    for (var i = 0; i < roomInfo.seats.length; i++) {
        var copyCountMap;
        var localSeat = game.gameSeats[i];
        if (localSeat.copyCountMap) {
            copyCountMap = localSeat.copyCountMap;
        } else {
            copyCountMap = localSeat.countMap;
        }
        if (!localSeat.isTing) {   //  如果操作的玩家非听牌状态即不参与计算
            continue;
        }
        for (var pai in copyCountMap) {
            var jiType = constant.getJiPaiTypeByPai(pai);
            if (jiType !== -1 && copyCountMap[pai] > 0) {  // 是鸡牌
                if (!isChongFengJi(game, jiType + '')) {  // 没选冲锋鸡不参与计算分数
                    continue;
                }
                for (var s = 0; s < roomInfo.seats.length; s++) {
                    var seatData = game.gameSeats[s];
                    if (seatData[JpaiNameMap[pai]] === undefined) {
                        seatData[JpaiNameMap[pai]] = [];
                        seatData[JpaiNameMap[pai] + "_num"] = 0;
                        seatData[JpaiNameMap[pai] + "_sum"] = 0;
                    }
                    var score = constant.JiPaiScore[jiType].other;
                    if (seatData.seatIndex === game.gameSeats[i].seatIndex) {
                        seatData[JpaiNameMap[pai]].push({ seatId: localSeat.seatIndex, score: score * copyCountMap[pai] * (roomInfo.seats.length - 1) });
                        seatData[JpaiNameMap[pai] + "_sum"] += score * copyCountMap[pai] * (roomInfo.seats.length - 1);
                        seatData[JpaiNameMap[pai] + "_num"] += copyCountMap[pai];

                    } else {
                        seatData[JpaiNameMap[pai] + "_sum"] -= score * copyCountMap[pai];
                        seatData[JpaiNameMap[pai]].push({ seatId: localSeat.seatIndex, score: - (score * copyCountMap[pai]) });
                    }
                }
            }
        }
    }
};

var getSeatDataBySeatIndex = function (game, seatIndex) {
    for (var i = 0; i < game.gameSeats.length; i++) {
        if (game.gameSeats[i].seatIndex === seatIndex) {
            return game.gameSeats[i];
        }
    }
    return {};
};


var isChongFengJi = function (game, type) {
    if (!game.chongFengJi) {
        return false;
    }
    var index = Object.keys(game.chongFengJi).indexOf(type);
    return index != -1 ? true : false;
};


// var findFanJiPaiTypeCountInChuPaiRecord = function (game, roomInfo, fanPai) {
//     var fanTypeCounts = {};
//     var jiPaiList = fanPai.filter(function (pai) {
//         return constant.getJiPaiTypeByPai(pai) !== -1;
//     });
//     for (var i = 0; i < roomInfo.seats.length; ++i) {
//         fanTypeCounts[game.gameSeats[i].seatIndex] = {};
//         jiPaiList.forEach(function (pai) {
//             var type = constant.getJiPaiTypeByPai(pai);
//             if (fanTypeCounts[game.gameSeats[i].seatIndex][type] === undefined) {
//                 fanTypeCounts[game.gameSeats[i].seatIndex][type] = {};
//             }
//             fanTypeCounts[game.gameSeats[i].seatIndex][type][pai] = 0;
//         });
//     }

//     if (jiPaiList.length <= 0) {
//         return fanTypeCounts;
//     }

//     for (var k = 0; k < game.chuJiPaiRecord.length; k++) {
//         var record = game.chuJiPaiRecord[k];
//         if (!getSeatDataBySeatIndex(game, record.turnSeat).isTing) {   //  如果出牌的玩家非听牌状态即不参与计算
//             continue;
//         }
//         if (~jiPaiList.indexOf(record.pai)) {
//             fanTypeCounts[record.turnSeat][record.type][record.pai]++;
//         }
//     }
//     return fanTypeCounts;
// };




exports.calculationJiPaiRecordScore = function (game, roomInfo) {
    // 1. 计算鸡牌记录分数 
    log.debug('all====>:', game.JiPaiRecord);
    var JpaiNameMap = constant.JpaiNameMap;
    for (var k = 0; k < game.JiPaiRecord.length; k++) {
        var record = game.JiPaiRecord[k];
        if (!getSeatDataBySeatIndex(game, record.operSeat).isTing) {   //  如果操作的玩家非听牌状态即不参与计算
            continue;
        }
        if (!isChongFengJi(game, record.type + '')) {  // 没选冲锋鸡不参与计算分数
            continue;
        }
        log.debug('calculation===>:', record);
        var jiType = constant.getJiPaiTypeByPai(record.pai);
        var score = constant.JiPaiScore[jiType].other;
        var num = constant.operNum[record.oper.oper];
        for (var i = 0; i < roomInfo.seats.length; ++i) {
            var seatData = game.gameSeats[i];
            if (seatData[JpaiNameMap[record.pai]] === undefined) {
                seatData[JpaiNameMap[record.pai]] = [];
                seatData[JpaiNameMap[record.pai] + "_num"] = 0;
                seatData[JpaiNameMap[record.pai] + "_sum"] = 0;
            }
            if (record.turnSeat === record.operSeat) {  //计算普通鸡（冲锋鸡）
                if (record.oper.isChongFengJi) {
                    score = constant.JiPaiScore[jiType].frist;
                }
                if (seatData.seatIndex === record.turnSeat) { // 是自己打出的鸡牌没被其它玩家操作
                    seatData[JpaiNameMap[record.pai]].push({ seatId: record.operSeat, score: num * score * (roomInfo.seats.length - 1) });
                    seatData[JpaiNameMap[record.pai] + "_sum"] += num * score * (roomInfo.seats.length - 1); // 累积分数记录
                    seatData[JpaiNameMap[record.pai] + "_num"] += num;
                } else {
                    seatData[JpaiNameMap[record.pai] + "_sum"] -= num * score; // 累积分数记录
                    seatData[JpaiNameMap[record.pai]].push({ seatId: record.operSeat, score: -(num * score) });
                }

            } else {     //计算责任鸡分
                // 是自己打出的鸡牌被其它玩家操作
                if (record.operSeat === seatData.seatIndex) {   //操作牌的用户
                    if (record.oper.isChongFengJi) {
                        var zerenPaiScore = constant.JiPaiScore[jiType].frist;
                        var otherPaiScore = 0;
                        if (num - 1 > 0) {
                            otherPaiScore = (num - 1) * constant.JiPaiScore[jiType].other;
                        }
                        if (roomInfo.seats.length === 2) {
                            seatData[JpaiNameMap[record.pai]].push({ seatId: record.operSeat, score: zerenPaiScore + otherPaiScore });
                            seatData[JpaiNameMap[record.pai] + "_sum"] += zerenPaiScore + otherPaiScore;
                        } else {
                            seatData[JpaiNameMap[record.pai]].push({ seatId: record.operSeat, score: (zerenPaiScore + otherPaiScore) + (num * constant.JiPaiScore[jiType].other * (roomInfo.seats.length - 2)) });
                            seatData[JpaiNameMap[record.pai] + "_sum"] += (zerenPaiScore + otherPaiScore) + (num * constant.JiPaiScore[jiType].other * (roomInfo.seats.length - 2));
                        }
                    } else {
                        seatData[JpaiNameMap[record.pai]].push({ seatId: record.operSeat, score: num * constant.JiPaiScore[jiType].other * (roomInfo.seats.length - 1) });
                        seatData[JpaiNameMap[record.pai] + "_sum"] += num * constant.JiPaiScore[jiType].other * (roomInfo.seats.length - 1); // 累积分数记录
                    }
                    seatData[JpaiNameMap[record.pai] + "_num"] += num;

                } else if (record.turnSeat === seatData.seatIndex) { // 出鸡的用户
                    if (record.oper.isChongFengJi) {
                        zerenPaiScore = constant.JiPaiScore[jiType].frist;
                        otherPaiScore = 0;
                        if (num - 1 > 0) {
                            otherPaiScore = (num - 1) * constant.JiPaiScore[jiType].other;
                        }
                        seatData[JpaiNameMap[record.pai] + "_sum"] -= (zerenPaiScore + otherPaiScore);
                        seatData[JpaiNameMap[record.pai]].push({ seatId: record.operSeat, score: - (zerenPaiScore + otherPaiScore) });

                    } else {
                        seatData[JpaiNameMap[record.pai] + "_sum"] -= (num * constant.JiPaiScore[jiType].other);
                        seatData[JpaiNameMap[record.pai]].push({ seatId: record.operSeat, score: - (num * constant.JiPaiScore[jiType].other) });
                    }

                } else { // 其它几家
                    seatData[JpaiNameMap[record.pai] + "_sum"] -= (num * constant.JiPaiScore[jiType].other);
                    seatData[JpaiNameMap[record.pai]].push({ seatId: record.operSeat, score: - (num * constant.JiPaiScore[jiType].other) });
                }

            }
        }
    }
    calculationJiPaiHoldsScore(game, roomInfo); // 2. 计算手牌鸡牌
    calculationShangXiaJiPaiScore(game, roomInfo); // 3. 计算上下鸡分数
    // console.log(game.gameSeats[0]);
    //  console.log(game.gameSeats[1]);
    //   console.log(game.gameSeats[2]);
    //    console.log(game.gameSeats[3]);
};

exports.includeAllPais = function (game, roomInfo) {
    for (var i = 0; i < roomInfo.seats.length; i++) {
        var seatData = game.gameSeats[i];
        seatData.allCountMap = _.cloneDeep(seatData.countMap);
        seatData.pengs.forEach(function (pai) {
            if (seatData.allCountMap[pai] != null) {
                seatData.allCountMap[pai]++;
                seatData.allCountMap[pai]++;
                seatData.allCountMap[pai]++;
            } else {
                seatData.allCountMap[pai] = 0;
                seatData.allCountMap[pai]++;
                seatData.allCountMap[pai]++;
                seatData.allCountMap[pai]++;
            }
        });
        var addPais = seatData.angangs.concat(seatData.diangangs).concat(seatData.wangangs);
        addPais.forEach(function (pai) {
            if (seatData.allCountMap[pai] != null) {
                seatData.allCountMap[pai]++;
                seatData.allCountMap[pai]++;
                seatData.allCountMap[pai]++;
                seatData.allCountMap[pai]++;
            } else {
                seatData.allCountMap[pai] = 0;
                seatData.allCountMap[pai]++;
                seatData.allCountMap[pai]++;
                seatData.allCountMap[pai]++;
                seatData.allCountMap[pai]++;
            }
        });
    }
};

var calculationShangXiaJiPaiScore = function (game, roomInfo) {
    var calculation = function (seatData, nextSeatData, jiPai, score, len, chuPaiNum, field) {
        var count = seatData.allCountMap[jiPai] ? seatData.allCountMap[jiPai] : 0;
        if (nextSeatData.seatIndex === seatData.seatIndex) {
            nextSeatData[field].push({ seatId: seatData.seatIndex, score: score * count * len + chuPaiNum * score });
            nextSeatData[field + "_sum"] += score * count * len + chuPaiNum * score;
            nextSeatData[field + "_num"] += count + chuPaiNum;
        } else {
            nextSeatData[field + "_sum"] -= score * count + chuPaiNum * score;
            nextSeatData[field].push({ seatId: seatData.seatIndex, score: -(score * count + chuPaiNum * score) });
        }
    };
    game.shangXiaJi = true;
    if (game.shangXiaJi) {
        var shangxiaJiPais = [game.huPaiFanJi[1], game.huPaiFanJi[2]];
        exports.includeAllPais(game, roomInfo);
        shangxiaJiPais.forEach(function (jiPai, index) {
            for (var i = 0; i < roomInfo.seats.length; i++) {
                var seatData = game.gameSeats[i];
                var jiPaiType = exports.getConfigJiPaiTypeByPai(game, jiPai);
                if (seatData.isTing &&
                    ((seatData.allCountMap[jiPai] !== undefined && seatData.allCountMap[jiPai] > 0))) {
                    for (var j = 0; j < roomInfo.seats.length; j++) {
                        var nextSeatData = game.gameSeats[j];
                        var score = 1;
                        if (jiPaiType !== -1) {
                            score = constant.JiPaiScore[jiPaiType].frist;
                        }
                        var chuJiPaiNum = 0;
                        if (index === 0) {
                            if (nextSeatData.shangJiScore === undefined) {
                                nextSeatData.shangJiScore = [];
                                nextSeatData.shangJiScore_sum = 0;
                                nextSeatData.shangJiScore_num = 0;
                            }
                            calculation(seatData, nextSeatData, jiPai, score, (roomInfo.seats.length - 1), chuJiPaiNum, "shangJiScore");
                        }
                        else {

                            if (nextSeatData.xiaJiScore === undefined) {
                                nextSeatData.xiaJiScore = [];
                                nextSeatData.xiaJiScore_sum = 0;
                                nextSeatData.xiaJiScore_num = 0;
                            }
                            calculation(seatData, nextSeatData, jiPai, score, (roomInfo.seats.length - 1), chuJiPaiNum, "xiaJiScore");
                        }

                    }

                }
            }

        });

    }
};

exports.getJiPaiRecord = function (game) {
    return game.JiPaiRecord;
};

exports.cleanJiPaiRecord = function (game) {
    game.JiPaiRecord = [];
};

